//
//  ViewController.m
//  KeyEquivalentDemo
//
//  Created by 张昭 on 16/8/31.
//  Copyright © 2016年 张昭. All rights reserved.
//

#import "ViewController.h"

#import <Carbon/Carbon.h>

@interface ViewController ()

//@property (nonatomic, strong) 
@end

@implementation ViewController

char* getCmdResult(const char *command)
{
    char result[1024];
    FILE *fp;
    fp = popen(command, "r");
    if (fp == NULL) {
        perror("popen failed.");
        exit(1);
    }
    
    while (fgets(result, sizeof(result), fp) != NULL) {
        if (result[strlen(result) - 1] == '\n') {
            result[strlen(result) - 1] = '\0';
        }
    }
    pclose(fp);
    return strdup(result);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    NSTextField *text = [NSTextField textFieldWithString:@"fjldsajlkfsafjldsajlkfsafjldsajlkfsafjldsajlkfsafjldsajlkfsafjldsajlkfsa"];
    [self.view addSubview:text];
    text.frame = NSMakeRect(100, 100, 200, 150);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleHotKeyEvent:) name:@"HotKeyEvent" object:nil];
    [self costomHotKey];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/Frameworks/AppKit.framework/Resources/StandardKeyBinding.dict"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSWorkspace *spacce = [NSWorkspace sharedWorkspace];
        NSLog(@"=======:%d bundldID:%@",spacce.frontmostApplication.processIdentifier,spacce.frontmostApplication.bundleIdentifier);
    });
    [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown|NSEventMaskFlagsChanged handler:^NSEvent * _Nullable(NSEvent * _Nonnull event) {
        NSLog(@"%@",event);
        NSUInteger flags = event.modifierFlags & NSEventModifierFlagDeviceIndependentFlagsMask;
        if (flags == NSEventModifierFlagCapsLock) {
            NSLog(@"caps");
        } else if (flags == NSEventModifierFlagShift) {
            NSLog(@"shift");
        }else if (flags == NSEventModifierFlagControl) {
            NSLog(@"ctl");
        }else if (flags == NSEventModifierFlagOption && event.keyCode == kVK_ANSI_C) {
            NSLog(@"OPTION");
//            execute();
        }else if (flags == NSEventModifierFlagCommand) {
            NSLog(@"cmd");
        }else if (flags == NSEventModifierFlagNumericPad) {
            NSLog(@"number");
        }else if (flags == NSEventModifierFlagHelp) {
            NSLog(@"help");
        }else if (flags == NSEventModifierFlagFunction) {
            NSLog(@"function");
        }else if (flags == NSEventModifierFlagDeviceIndependentFlagsMask) {
            NSLog(@"Independent");
        }
        return  event;
    }];
//    NSLog(@"===dic:%@",dic);
}
- (void)mouseDown:(NSEvent *)event {
    [super mouseDown:event];
    execute();
    
//    [self execute];
//    pid_t pid = isProcessRunning(@"taijiperimeter");
//    pid_t ret = [self ParentPidOf:10328];
//    NSString *processPath = getProcessPath(10328);
//    NSLog(@"pid==:%d parent:%d path:%@",pid,ret,processPath);
//    PostKeyboardEvent(kVK_ANSI_Q,NO,kCGEventFlagMaskCommand);
}


- (void)handleHotKeyEvent:(NSNotification *)noti {

    NSInteger hotKeyID = [[noti.userInfo objectForKey:@"hotKeyID"] intValue];
    
    if ( hotKeyID == 4) {
        self.view.window.backgroundColor = [NSColor blackColor];
        execute();
    }
}


- (void)keyUp:(NSEvent *)theEvent {
    NSLog(@"%hu", theEvent.keyCode);
}

// 注册快捷键
- (void)costomHotKey {
    
    // 1、声明相关参数
    EventHotKeyRef myHotKeyRef;
    EventHotKeyID myHotKeyID;
    EventTypeSpec myEvenType;
    myEvenType.eventClass = kEventClassKeyboard;    // 键盘类型
    myEvenType.eventKind = kEventHotKeyPressed;     // 按压事件
    
    // 2、定义快捷键
    myHotKeyID.signature = 'yuus';  // 自定义签名
    myHotKeyID.id = 4;              // 快捷键ID

#pragma mark 注册快捷键
    // 3、注册快捷键
    // 参数一：keyCode; 如18代表1，19代表2，21代表4，49代表空格键，36代表回车键
    // 快捷键：command+4
    OSStatus status = RegisterEventHotKey(kVK_ANSI_C,optionKey, myHotKeyID, GetApplicationEventTarget(), kEventHotKeyExclusive, &myHotKeyRef);
    NSLog(@"status: %d",status);
    // 快捷键：command+option+4
//    RegisterEventHotKey(21, cmdKey + optionKey, myHotKeyID, GetApplicationEventTarget(), 0, &myHotKeyRef);

    
    // 5、注册回调函数，响应快捷键
    InstallApplicationEventHandler(&hotKeyHandler, 1, &myEvenType, NULL, NULL);

    
}



// 4、自定义C类型的回调函数
OSStatus hotKeyHandler(EventHandlerCallRef nextHandler, EventRef anEvent, void *userData) {
    
    EventHotKeyID hotKeyRef;
    
    GetEventParameter(anEvent, kEventParamDirectObject, typeEventHotKeyID, NULL, sizeof(hotKeyRef), NULL, &hotKeyRef);
    
    unsigned int hotKeyId = hotKeyRef.id;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"HotKeyEvent" object:nil userInfo:@{@"hotKeyID": @(hotKeyId)}];
    
    switch (hotKeyId) {
        case 4:
            // do something
            NSLog(@"%d", hotKeyId);
           

            break;
        default:
            break;
    }
    return noErr;
}
void execute() {
  CGEventSourceRef src =
    CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
    
    CGEventTapLocation loc = kCGSessionEventTap; // kCGSessionEventTap also works

    CGKeyCode inputKeyCode = kVK_ANSI_C;
    CGEventRef copyCommandDown = CGEventCreateKeyboardEvent(nil, inputKeyCode, YES);
    CGEventSetFlags(copyCommandDown, kCGEventFlagMaskCommand);
    CGEventPost(loc, copyCommandDown);

    CGEventRef copyCommandup = CGEventCreateKeyboardEvent(nil, inputKeyCode, NO);
    CGEventSetFlags(copyCommandup, kCGEventFlagMaskCommand);
    CGEventPost(loc, copyCommandup);

  CFRelease(src);
}





- (IBAction)commandOneBtnClicked:(NSButton *)sender {
    self.view.window.backgroundColor = [NSColor redColor];
}

- (IBAction)commandTwoBtnClicked:(NSButton *)sender {
    self.view.window.backgroundColor = [NSColor yellowColor];
}

- (IBAction)commandThreeBtnClicked:(NSButton *)sender {
    self.view.window.backgroundColor = [NSColor greenColor];
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}

@end
